//
//  BKLineChartView.m
//  智能备考学习
//
//  Created by 盛超 on 2018/1/22.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "BKLineChartView.h"
#define bounceX 20
#define bounceY 30
#define PaddingWidth 15
//#define YMax 10000

@interface BKLineChartView ()
@property (nonatomic, strong) CAShapeLayer *lineChartLayer;
@property (nonatomic, strong) CAGradientLayer *gradientLayer;
@property (nonatomic,strong) UIBezierPath *path;
@property (nonatomic,strong) UILabel *textLabel;
@property (nonatomic,strong) NSMutableArray *XarrMonth;
@property (nonatomic,strong) NSMutableArray *XarrWeek;
@property (nonatomic,strong) NSMutableArray *YarrMonth;
@property (nonatomic,strong) NSMutableArray *YarrWeek;
@property (nonatomic,strong) NSMutableArray *pointArr;
@property (nonatomic,strong) NSMutableArray *YValues;
@property (nonatomic,copy) NSString *title;

@end

@implementation BKLineChartView {
    CGFloat YMax;
    CGFloat YMin;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}


#pragma mark - 创建X轴数据
- (void)createLabelX {
    CGFloat month = self.Xarr.count;
    for (NSInteger i = 0; i<month; i++) {

        UILabel *labelX = [[UILabel alloc] initWithFrame:CGRectMake(25+(self.frame.size.width-2*bounceX-50)/(month-1) * i +1+bounceX/2 - PaddingWidth, self.frame.size.height-bounceY,40, bounceY/2)];
        labelX.tag = 1000+i;
        labelX.text = self.Xarr[i];
        //labelX.backgroundColor = [UIColor blueColor];
        labelX.text = [labelX.text stringByReplacingOccurrencesOfString:@"-" withString:@"."];
        if (labelX.text.length>6) {
            labelX.text = [labelX.text substringFromIndex:5];
        }
        labelX.font = [UIFont systemFontOfSize:10];
        labelX.textColor = [UIColor colorWithHex:0xcfcfcf];
        labelX.textAlignment = NSTextAlignmentCenter;

        [self addSubview:labelX];
        
        if (i==0) {
            UILabel *labelXname = [[UILabel alloc] initWithFrame:CGRectMake(self.width-bounceX,labelX.y,40,bounceY/2)];
            labelXname.font = [UIFont systemFontOfSize:10];
            labelXname.textColor = [UIColor colorWithHex:0xcfcfcf];
            labelXname.textAlignment = NSTextAlignmentLeft;
            labelXname.text = @"日期";
            [self addSubview:labelXname];
        }
    }
    
 
}

#pragma mark - 创建Y轴数据
- (void)createlabelY {
    [self handleMaxY:_Yarr];
    [self handelMinY:_Yarr];
    
    CGFloat differenceYValue = YMax - YMin;
    for (NSInteger i = 0; i<5; i++) {
        UILabel *labelY = [[UILabel alloc] initWithFrame:CGRectMake(0, (self.frame.size.height - 2 * bounceY)/5 *i + bounceY-9, 18, bounceY/2.0)];
        labelY.tag = 2000+i;
        labelY.text = [NSString stringWithFormat:@"%d",(int)(differenceYValue/5 *(5-i))];
        labelY.font = [UIFont systemFontOfSize:10];
        labelY.textColor = [UIColor colorWithHex:0xcfcfcf];
        labelY.textAlignment = NSTextAlignmentRight;
        //labelY.backgroundColor = [UIColor blueColor];
        [self addSubview:labelY];
        if (i==0) {
            UILabel *labelYname = [[UILabel alloc] initWithFrame:CGRectMake(0,labelY.y-20,40,20)];
            labelYname.font = [UIFont systemFontOfSize:10];
            labelYname.textColor = [UIColor colorWithHex:0xcfcfcf];
            labelYname.textAlignment = NSTextAlignmentCenter;
            labelYname.text = @"能力值";
            [self addSubview:labelYname];
        }
        UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(bounceX,(self.frame.size.height - 2 * bounceY)/5 *i + bounceY,self.frame.size.width-bounceX*2, 0.5)];
        line.backgroundColor = [UIColor colorWithR:230 g:230 b:230 a:0.5];
        [self addSubview:line];
    }
}

//绘制图表
- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, 0.5);
    CGContextSetRGBStrokeColor(context,207.0/255,207.0/255,207.0/255,0.5);
    CGContextMoveToPoint(context, bounceX, bounceY-5);
    CGContextAddLineToPoint(context, bounceX, rect.size.height-bounceY);//Y轴
    CGContextAddLineToPoint(context, rect.size.width-bounceX, rect.size.height-bounceY);//X轴
    CGContextStrokePath(context);
}

- (void)drawLine {
    self.pointArr = [NSMutableArray array];
    self.YValues = [NSMutableArray array];
    UIBezierPath * path = [[UIBezierPath alloc]init];
    for(NSInteger i = 0 ; i<self.Xarr.count ; i++ ) {
        UILabel *label = (UILabel*)[self viewWithTag:1000+i];//根据横坐标上的label获取x坐标的值
        NSString *arc =  self.Yarr[i];//arc4random()%(self.Yarr.count*100);  //折线点目前给的是随机数
        CGPoint point = CGPointMake(label.frame.origin.x+label.frame.size.width/2, bounceY+(YMax-arc.floatValue) /(YMax-YMin) * (self.frame.size.height - bounceY*2));
        
        if (i==0) {
            [path moveToPoint:point];
        } else {
           
            CGPoint from = ((NSValue*)(self.pointArr[i-1])).CGPointValue;
            CGPoint to = point;
            CGPoint midPoint = [self midPointBetweenPoint1:from andPoint2:to];
            [path addQuadCurveToPoint:midPoint controlPoint:[self controlPointBetweenPoint1:midPoint andPoint2:from]];
            [path addQuadCurveToPoint:to controlPoint:[self controlPointBetweenPoint1:midPoint andPoint2:to]];
        }
        
        [self.pointArr addObject:[NSValue valueWithCGPoint:point]];
        [self.YValues addObject:arc];
    }
    
    self.lineChartLayer = [CAShapeLayer layer];
    self.lineChartLayer.path = path.CGPath;
    self.lineChartLayer.strokeColor = [UIColor whiteColor].CGColor;
    self.lineChartLayer.fillColor = [[UIColor clearColor] CGColor];
    // 默认设置路径宽度为0，使其在起始状态下不显示
    self.lineChartLayer.lineWidth = 1;
    self.lineChartLayer.lineCap = kCALineCapRound;
    self.lineChartLayer.lineJoin = kCALineJoinRound;
    [self doAnimationWithLayer:self.lineChartLayer];
    
    [self.layer addSublayer:self.lineChartLayer];//直接添加导视图上
}

//计算绘制贝塞尔曲线controlPoint
- (CGPoint)controlPointBetweenPoint1:(CGPoint)point1 andPoint2:(CGPoint)point2 {
    CGPoint controlPoint = [self midPointBetweenPoint1:point1 andPoint2:point2];
    CGFloat diffY = abs((int) (point2.y - controlPoint.y));
    if (point1.y < point2.y)
        controlPoint.y += diffY;
    else if (point1.y > point2.y)
        controlPoint.y -= diffY;
    return controlPoint;
}

- (CGPoint)midPointBetweenPoint1:(CGPoint)point1 andPoint2:(CGPoint)point2 {
    return CGPointMake((point1.x + point2.x) / 2, (point1.y + point2.y) / 2);
}


//点和数值
- (void)addPointCircle {
    
    for (NSInteger i = 0; i<self.pointArr.count; i++) {
        CGPoint point = [self.pointArr[i] CGPointValue];
        UILabel * falglabel = [[UILabel alloc]initWithFrame:CGRectMake(point.x-13, point.y-20  , 30, 15)];
        falglabel.textAlignment = NSTextAlignmentCenter;
        falglabel.textColor = [UIColor lightGrayColor];
        falglabel.tag = 3000+ i;
        falglabel.text = self.YValues[i];
        falglabel.font = [UIFont systemFontOfSize:8.0];
        [self addSubview:falglabel];
        
        UIImageView * circle = [[UIImageView alloc]initWithFrame:CGRectMake(point.x-5, point.y-5,10,10)];
        circle.backgroundColor = [UIColor whiteColor];
        circle.layer.cornerRadius = 5;
        circle.layer.borderWidth = 2;
        circle.layer.borderColor = _lineChartBackgroundColor.CGColor;
        circle.layer.masksToBounds = YES;
        
        circle.tag = 4000 + i;
        [self addSubview:circle];
    }
    
}

//折线动画
- (void)doAnimationWithLayer:(CAShapeLayer *)layer{
    CABasicAnimation * baseAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    baseAnimation.duration = 1;
    baseAnimation.fromValue = @0.0;
    baseAnimation.toValue = @1.0;
    baseAnimation.repeatCount = 1;
    [layer addAnimation:baseAnimation forKey:@"strokeAnimation"];
}

//背景填充
- (void)drawGredientLayer{
    self.gradientLayer = [CAGradientLayer layer];
    self.gradientLayer.frame = self.bounds;
    
    UIColor *color1 = _lineChartBackgroundColor;
    UIColor *color2 = _lineChartBackgroundColor2;
    self.gradientLayer.colors = @[(__bridge id)color1.CGColor,(__bridge id)color2.CGColor];
    
    self.gradientLayer.locations=@[@0.0,@1.0];
    self.gradientLayer.startPoint = CGPointMake(0.0,0.0);
    self.gradientLayer.endPoint = CGPointMake(0,1);
    
    CAShapeLayer *arc = [CAShapeLayer layer];
    UIBezierPath *path = [UIBezierPath bezierPath];
   // UILabel *label0 = (UILabel*)[self viewWithTag:1000];
    [path moveToPoint:CGPointMake(0,self.height)];
   // [path addLineToPoint:CGPointMake(0,self.height/2)];

    for(NSInteger i = 0 ; i<self.Xarr.count ; i++ ) {
        UILabel *label = (UILabel*)[self viewWithTag:1000+i];
        NSString* arc =  self.YValues[i];
        CGPoint point = CGPointMake(label.frame.origin.x+label.frame.size.width/2, bounceY +(YMax - arc.floatValue) /(YMax-YMin) * (self.frame.size.height - bounceY*2));
        NSLog(@"%f",point.y);
        if (i==0) {
            [path moveToPoint:CGPointMake(point.x,self.height-bounceY)];
            [path addLineToPoint:point];
        } else {
            
            CGPoint from = ((NSValue*)(self.pointArr[i-1])).CGPointValue;
            CGPoint to = point;
            CGPoint midPoint = [self midPointBetweenPoint1:from andPoint2:to];
            [path addQuadCurveToPoint:midPoint controlPoint:[self controlPointBetweenPoint1:midPoint andPoint2:from]];
            [path addQuadCurveToPoint:to controlPoint:[self controlPointBetweenPoint1:midPoint andPoint2:to]];
        }
        
        if (i==self.Xarr.count-1) {
            [path addLineToPoint:CGPointMake(point.x,self.height-bounceY)];
        }
    }
    
    arc.path = path.CGPath;
    self.gradientLayer.mask = arc;
    
    CABasicAnimation * baseAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    baseAnimation.duration = 1;
    baseAnimation.fromValue = @0.0;
    baseAnimation.toValue = @1.0;
    baseAnimation.repeatCount = 1;
    
    [self.layer addSublayer:self.gradientLayer];
    
//    //标题
//    [self.textLabel removeFromSuperview];
//    UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, self.height/2-7, kWidth, 14)];
//    self.textLabel = textLabel;
//    textLabel.font = [UIFont systemFontOfSize:14.0f];
//    textLabel.textColor = [UIColor colorWithHex:0x276899];
//    textLabel.textAlignment = NSTextAlignmentCenter;
//    textLabel.text = self.title;
//    [self addSubview:textLabel];
}

#pragma mark - 绘制图表
- (void)setLineChartBackgroundColor:(UIColor *)lineChartBackgroundColor {
    _lineChartBackgroundColor = lineChartBackgroundColor;
}

- (void)setXarr:(NSArray *)Xarr {
    _Xarr = Xarr;
}

- (void)setYarr:(NSArray *)Yarr {
    _Yarr = Yarr;
    
    for (NSInteger i = 0; i<self.Xarr.count; i++) {
        UILabel *label =(UILabel*)[self viewWithTag:1000+i];
        UILabel *label2 =(UILabel*)[self viewWithTag:2000+i];
        UILabel *label3 =(UILabel*)[self viewWithTag:3000+i];
        UILabel *label4 =(UILabel*)[self viewWithTag:4000+i];
        [label removeFromSuperview];
        [label2 removeFromSuperview];
        [label3 removeFromSuperview];
        [label4 removeFromSuperview];
    }
    
    [self.lineChartLayer removeFromSuperlayer];
    [self.gradientLayer removeFromSuperlayer];
    
    [self createLabelX];
    [self createlabelY];
    [self drawLine];
    [self drawGredientLayer];
    [self addPointCircle];
}

- (void)handleMaxY:(NSArray*)array {
    if (array.count>1) {
        NSInteger vlaue = ((NSString*)(array.firstObject)).integerValue;
        for (NSInteger i = 1; i<array.count; i++) {
            NSInteger value2 = ((NSString*)(array[i])).integerValue;
            if (value2 >= vlaue) {
                vlaue = value2;
            }
        }
        NSInteger sum = 0;
        while (vlaue) {
            sum++;
            vlaue = vlaue/10;
            NSLog(@"%ld",vlaue);
        }
        
        NSString *string = @"1";
        for (NSInteger i = 0; i<sum; i++) {
            string = [NSString stringWithFormat:@"%@0",string];
        }
        YMax = string.integerValue;
        NSLog(@"YMax=%f",YMax);
    }
}

- (void)handelMinY:(NSArray*)array {
    if (array.count>1) {
        NSInteger vlaue = ((NSString*)(array.firstObject)).integerValue;
        for (NSInteger i = 1; i<array.count; i++) {
            NSInteger value2 = ((NSString*)(array[i])).integerValue;
            if (value2 <= vlaue) {
                vlaue = value2;
            }
        }
       
        if (vlaue>=500) {
            vlaue = vlaue-500;
        } else {
            vlaue = 0;
        }
        YMin = vlaue;
        
        NSLog(@"YMin=%f",YMin);
    }
}

@end
